
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:process_run/cmd_run.dart';
import 'package:rfid/event/id_event.dart';
import 'package:rfid/event/wrong_way_event.dart';
import 'package:rfid/page/mine_page.dart';
import '../entity/current_task_entity.dart';
import '../entity/reader_entity.dart';
import '../entity/setting_entity.dart';
import '../event/check_result_event.dart';
import '../event/face_event.dart';
import '../event/lock_query_event.dart';
import '../event/lock_state_event.dart';
import '../event/qr_event.dart';
import '../event/user_id_event.dart';
import '../hive/hive_helper.dart';
import '../http/api.dart';
import '../log/logger_manager.dart';
import '../main.dart';
import '../socket/socket.dart';
import '../util/toast_util.dart';
import '../widget/auth_dialog.dart';
import '../widget/device_name_widget.dart';
import '../widget/dialog_widget.dart';
import '../widget/focus_killer.dart';
import 'borrow_result_page.dart';
import 'camera_page.dart';
import 'help_page.dart';

class Index extends StatefulWidget {
  const Index({Key? key}) : super(key: key);

  @override
  State<Index> createState() => _IndexState();

}

class _IndexState extends State<Index>  {

  bool useRfid = false;
  bool useReader = false;
  bool useLock = false;

  StreamSubscription? userSubscription;
  StreamSubscription? lockSubscription;
  StreamSubscription? wrongWaySubscription;
  StreamSubscription? lockQuerySubscription;
  StreamSubscription? idSubscription;
  StreamSubscription? faceSubscription;
  StreamSubscription? qrSubscription;


  @override
  initState() {
    super.initState();

    timer.setCountDownTime(fastCountdown: settingEntity.fastCountdown,
        normalCountdown: settingEntity.normalCountdown, slowCountdown: settingEntity.slowCountdown);

    eventFactory.on<CheckResultEvent>().listen((event) {
        if(event.cmd == 'locker_check'){
          useLock = true;
        }
        if(event.cmd == 'rfid_uhf_check'){
          useRfid = true;
        }
        if(event.cmd == 'card_reader_check'){
          useReader = true;
        }
        if(useReader && useRfid && useLock){
          _lockQuery();
        }

    });
    wrongWaySubscription = eventFactory.on<WrongWayEvent>().listen((event) {
      _lockQuery();
    });
    lockQuerySubscription = eventFactory.on<LockQueryEvent>().listen((event) {
       var list =  event.entity.list;
       if(list != null){
         for(var item in list){
           if(item.state == 0){
              DialogWidget().warnOpenDialog();
           }
         }
       }
    });

    userSubscription = eventFactory.on<UserIdEvent>().listen((event) {
      currentTask.uid = event.uid;
      _goAfterAuth();
    });

    faceSubscription = eventFactory.on<FaceEvent>().listen((event) {
      currentTask.uid = event.uid;
      _goAfterAuth(category: 'face');
    });

    idSubscription = eventFactory.on<IdEvent>().listen((event) {
      currentTask.uid = event.no;

      _goAfterAuth(category: 'icr',name: event.name);

    });

    qrSubscription = eventFactory.on<QrEvent>().listen((event) async {
      currentTask.uid = event.qr;
      _goAfterAuth(category: 'qrcode');
    });

    lockSubscription = eventFactory.on<LockStateEvent>().listen((event) {
      if(Get.isDialogOpen != null && Get.isDialogOpen!){
        Get.back();
      }
      if(event.state == 0){
        if(settingEntity.reader != null && settingEntity.reader!.isNotEmpty){
          try{
            var doors = settingEntity.reader!.where((element) => (element.addr == event.addr.toString()) && (element.lock == event.no.toString())).first;
            if(currentTask.uid!=null && currentTask.readerEntity != null){
              DialogWidget().doorOpenDialog(doors.doorNo,currentTask.readerEntity!);
            }else{
              DialogWidget().adminDoorOpenDialog(doors.doorNo);
            }
          }catch (e){
            print(e);
          }
        }else{
          toastWarn('未配置格口');
        }

      }else{
        if(Get.rawRoute != null && Get.rawRoute!.isFirst){
          if(currentTask.doorNo != null && currentTask.uid != null){
            Get.to(() => const BorrowResult());
          }
        }
      }
    });
    // socketHelper.add(checkReader());
    print('version = $version');

    _getVersion();
  }

  _goAfterAuth({category = 'uid',String? name}) async {
    if(Get.isDialogOpen != null && Get.isDialogOpen!){
      Get.back();
    }
    if(Get.isDialogOpen != null && Get.isDialogOpen!){
      Get.back();
    }
    // //办证
    // if(currentTask.task == Task.register){
    //   var data = await findReader(currentTask.uid,category:'icr_uid');
    //   if(data == null){
    //     DialogWidget().idBindDialog();
    //     return;
    //   }
    //   if(!data.validReader!){
    //     DialogWidget().idBindDialog();
    //     return;
    //   }
    //   currentTask.clear();
    //   DialogWidget().registerFailedDialog('身份证号已注册');
    //   return;
    // }
    var data = await findReader(currentTask.uid,category:category);
    if(data == null ||  data.no == null || data.no!.isEmpty){
      currentTask.clear();
      toastWarn('查找读者失败');
      tts.speak("查找读者失败");
      return;
    }
    if(name != null){
      data.name = name;
    }
    // if(!data.validReader!){
    //   currentTask.clear();
    //   toastWarn('读者卡未注册');
    //   tts.speak("读者卡未注册");
    //   return;
    // }
    currentTask.uid = data.no;
    currentTask.readerEntity = data;
    //个人中心
    if(currentTask.task == Task.toMine){
      _toMine(data);
      return;
    }
    //随机格口
    if(currentTask.task == Task.borrowWithoutDoor){
      if(settingEntity.reader != null && settingEntity.reader!.isNotEmpty){
        var least = 1000;
        SettingEntityReader? leastReader;
        for(var reader in settingEntity.reader!){
          var num = bookQueryByDoorNo(reader.doorNo!).where((element) => element.statue == 0).length;
          if(num < least){
            least = num;
            leastReader = reader;
          }
          if(least == 0){
            break;
          }
        }
        if(leastReader != null){
          currentTask.doorNo = leastReader.doorNo;
          currentTask.readerIp = leastReader.readerIp;
          currentTask.ant = leastReader.ant;
          currentTask.addr = leastReader.addr;
          currentTask.lock = leastReader.lock;
        }
      }

      socketHelper.add(lockOpen(addr: currentTask.addr!, no: currentTask.lock!));
      return;
    }
    //指定格口
    if(currentTask.task == Task.borrowWithDoor){
      _reqReaderInfo(data);
    }

    //人脸
    if(currentTask.task == Task.addFace){
      _addFace(data);
    }



  }

  _getVersion() async {
    getVersion().then((value) async {
      if(value != null){
        int code = value.verCode??0;
        if(code > versionCode){
          _update();
        }
      }
    });
  }
  _update() async {
    // 替换以下路径为你的exe文件路径
    var executable = '${settingEntity.executable}\\Updater.exe';
    var arguments = <String>['-app:rfid', '-host:${settingEntity.apiAddr}', '-device_id:${settingEntity.deviceNo?.replaceAll('device_id=', '')}', '-kind:library']; // 如果需要传递参数，则添加到这个列表中

    // 启动外部exe文件
    var result = await runExecutableArguments(executable, arguments);

    // 打印输出
    print('Exit code: ${result.exitCode}');
    print('Stdout: ${result.stdout}');
    print('Stderr: ${result.stderr}');
  }


  _lockQuery(){
    if(settingEntity.reader != null && settingEntity.reader!.isNotEmpty){
      var addrs = settingEntity.reader!.map((e) => e.addr).toSet();
      for(var addr in addrs){
        socketHelper.add(lockQuery(addr: addr!));
      }
    }else{
      toastWarn('未配置格口');
    }
  }

  _addFace(ReaderEntity? data) async {
      currentTask.uName = data!.name;
      Get.to(()=> const CameraPage());
  }

  _toMine(ReaderEntity? data) async {
    Get.to(()=> const Mine(),arguments: data);
  }

  _reqReaderInfo(ReaderEntity? data) async {
    if(data != null){
      if(currentTask.needCheckCount){
        if(data.currentBorrowCount! >= data.limitCount!){
          toastError("已至最大借书数量，请先还书");
          tts.speak("已至最大借书数量，请先还书");
          Future.delayed(const Duration(seconds: 2),(){
            currentTask.clear();
          });
          timer.cancel();
          Get.until((route) => route.isFirst);
          return;
        }
        if(data.currentBorrowList !=null ){
          for (var element in data.currentBorrowList!) {
            if(element.overdue!){
              toastError("借阅已超时，请先还书");
              tts.speak("借阅已超时，请先还书");
              Future.delayed(const Duration(seconds: 2),(){
                currentTask.clear();
              });
              timer.cancel();
              Get.until((route) => route.isFirst);
              return;
            }
          }
        }
      }
      currentTask.offset = data.limitCount!-data.currentBorrowCount!;
      socketHelper.add(lockOpen(addr: currentTask.addr!, no: currentTask.lock!));
    }else{
      timer.cancel();
      toastWarn("用户不存在");
      Get.until((route) => route.isFirst);
    }

  }

  @override
  void dispose() {
    // serialPortHelper.close();
    socketHelper.dispose();
    userSubscription?.cancel();
    userSubscription = null;
    lockSubscription?.cancel();
    lockSubscription = null;
    // readerSubscription?.cancel();
    // readerSubscription = null;
    wrongWaySubscription?.cancel();
    wrongWaySubscription = null;
    lockQuerySubscription?.cancel();
    lockQuerySubscription = null;
    idSubscription?.cancel();
    idSubscription = null;
    faceSubscription?.cancel();
    faceSubscription = null;
    qrSubscription?.cancel();
    qrSubscription = null;
    books.close();
    LoggerManager().close();
    super.dispose();
  }



  _appBar(){
    return Container(
      width: double.infinity,
      height: 42.h,
      padding: const EdgeInsets.only(left: 20,right: 20).w,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          deviceNameWidget(setting: true),
          InkWell(
            onTap: () async {
              Get.to(()=> const Help());
            },
            child: Row(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                focusKiller(),
                Icon(Icons.help,color: Colors.white,size: 20.sp,),
                Text(" 帮助",style: TextStyle(color: Colors.white,fontSize: 12.sp),)
              ],
            ),
          )

        ],
      ),
    );
  }


  _title(){
    return Container(
      margin: EdgeInsets.only(top: 60.h),
      child: _image("assets/images/title.png",240.w,60.h),
    );
  }

  _action(){
    return Container(
      margin: EdgeInsets.only(top: 30.h),
      child: InkWell(
        onTap: (){
          DialogWidget().borrowTypeDialog();
        },
        child: _image("assets/images/borrow.png",310.w,126.h),
      )
    );
  }


  _action2(){
    return Container(
      margin: EdgeInsets.only(top: 6.h),
      width: 310.w,
      height: 258.h,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          InkWell(
            onTap: (){
              DialogWidget().returnTypeDialog();
            },
            child: _image("assets/images/return.png",151.w,258.h),
          ),
          Column(
            children: [
              InkWell(
                  onTap: (){
                    currentTask.task = Task.toMine;
                    AuthDialog().authTypeDialog();

                  },
                  child: Column(children: [
                    _image("assets/images/my_borrow.png",151.w,126.h),
                  ],)
              ),
              SizedBox(height: 6.h,),
              InkWell(
                  onTap: (){
                    // readTxtFile();
                    // printFile();
                    // currentTask.task = Task.register;
                    // Get.to(()=>const RegisterSelect());
                    toastWarn('功能暂不开放');
                    //
                    //
                    // malloc.free(ptr);

                    // final ptr = malloc.allocate<Utf8>(100);
                    // ptr.value = 'Hello, World!'.toNativeUtf8();
                    //
                    // // final utf8String = ''.toNativeUtf8();
                    // getName(utf8String,100);
                    // print(utf8String.toDartString());

                  },
                  child: Column(children: [
                    _image("assets/images/register.png",151.w,126.h),
                  ],)
              )
            ],
          )


        ],
      ),
    );
  }

  _version(){
    return SizedBox(
      width: 310.w,
      height: 35.h,
      // margin: EdgeInsets.only(top: 56).h,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Text(settingEntity.publishName??'',style: TextStyle(color: Colors.white,fontSize: 12.sp)),
          Text('v$version',style: TextStyle(color: Colors.white,fontSize: 12.sp)),
        ],
      ),
    );
  }

  _image(name,width, height){
    return Image.asset(name,height: height, width: width, fit: BoxFit.fill,);
  }


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        width: double.infinity,
        height: double.infinity,
        decoration: const BoxDecoration(
          image: DecorationImage(
            fit: BoxFit.fill,
            image: AssetImage(
                "assets/images/bg.png",
            ),
          ),
        ),
        child: Column(
          children: [
            _appBar(),
            _title(),
            _action(),
            _action2(),
            SizedBox(height: 20.h,),
            _version(),

          ],
        ),
      ),
    );
  }
}

